package com.jservice.framework.freemarker.directive;

import com.jservice.framework.servlet.ServletContextHolderKit;
import com.jservice.framework.utils.StringUtils;
import com.jservice.framework.utils.WebUtils;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;

/**
 * 模板指令 - 瞬时消息(通过cookie实现)
 * 
 * @author cwledit
 * @version 2.0
 */
public class FlashMessageDirective extends BaseDirective  {

	/** "瞬时消息"属性名称 */
	public static final String FLASH_MESSAGE_ATTRIBUTE_NAME = FlashMessageDirective.class.getName() + ".FLASH_MESSAGE";
	/** 变量名称 */
	private static final String VARIABLE_NAME = "flashMessage";
	@SuppressWarnings("rawtypes")
	public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
		HttpServletRequest request = ServletContextHolderKit.getRequest();
		String message = WebUtils.getCookie(request,FLASH_MESSAGE_ATTRIBUTE_NAME);
		if(StringUtils.isNotEmpty(message)){
			if (body != null) {
				setLocalVariable(VARIABLE_NAME, message, env, body);
			}else{
				int indexOf = StringUtils.indexOf(message,":");
				if (indexOf != StringUtils.INDEX_NOT_FOUND){
					String type = StringUtils.substring(message,0,indexOf);
					String content = StringUtils.substring(message,indexOf+1);
					Writer out = env.getOut();
					out.write("$.message(\"" + type + "\", \"" + content + "\");");
				}
			}
		}
	}
}